<template>
  <div class="customer-order">
    <div class="title-tool" style="margin-bottom:12px;">
      <FilterInput v-model="queryData" :filter-list="filterList" line-feed show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" />
      <div :class="{'table-top-opeator-bar':!showMobilePage,'mobile-operate':showMobilePage}">
        <PlainCreateBtn v-if="hasRouteAuth('crm:customer:createSettle') || isAdmin" @click="toCreate">创建结算单</PlainCreateBtn>
        <el-dropdown placement="bottom">
          <el-button plain size="small" style="padding: 8px 13px;margin-left: 10px;">查看</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="toList">结算单</el-dropdown-item>
            <el-dropdown-item @click.native="toBill">每月账单</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <btnGroup
          v-if="hasRouteAuth('crm:customer:detailOrderExport')"
          ref="btnGroupRef"
          :list="[{
            label:'导出',
            exportApi:'/admin/client/order/list/export',
            exportName:'客户订单列表',
            beforeExport: beforeExport,
            type: 'export',
            auth: hasRouteAuth('crm:customer:detailOrderExport')
          }]"
          style="margin-left: 10px"
        />
      </div>
    </div>
    <div>
      <el-table
        v-loading="loading"
        ref="clientOrderRef"
        :data="clientOrder.items"
        :row-class-name="tableRowClassName"
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @sort-change="sortMethod"
        @select="selectTable"
        @select-all="selectTable">
        <EmptyPlaceholder slot="empty" mode="table" />
        <el-table-column align="center" type="selection" fixed="left" width="50"/>
        <el-table-column align="left" label="订单编号" width="190">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.orderId" is-can-click @handelClick="goOrderDetail(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="下单日期" width="120">
          <template slot-scope="scope">
            <div v-if="scope.row.orderTime">{{ scope.row.orderTime | standardFormatNoHour('YYYY/MM/DD') }}</div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="联系人" min-width="100">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.contactPerson"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="销售" min-width="100">
          <template slot-scope="scope">
            <CheckUserInfo :user-id="scope.row.marketId" :label="scope.row.market" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="账号" min-width="100">
          <template slot-scope="scope">
            <resource-info
              v-if="scope.row.orderType !== 6"
              :resource-name="scope.row.resourceName"
              :account-name-organization="scope.row.accountNameOrganization"
              :account-name-platform="scope.row.accountNamePlatform"
              :resource-id="scope.row.orderInfo.resourceCode"
              account-belong-name="none"
            />
            <span v-else>包含多个账号</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="下单平台" min-width="100">
          <template slot-scope="scope">
            <div class="flex-center" style="color: #999">
              <platformIcon :data="scope.row.orderPlatform" />
              <ToolTip :content="scope.row.orderPlatform" />
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable align="left" label="逾期天数" min-width="100" prop="overdueDayNum">
          <template slot-scope="scope">
            <span v-if="scope.row.overdueDayNum === '未设账期'" style="cursor:pointer;color: #406EFF;" @click="levelDialogShow">调整账期</span>
            <span v-else-if="scope.row.overdueDayNum" style="color:#FF504F;">{{ scope.row.overdueDayNum }}</span>
            <span v-else style="color:#FF504F;">0</span>
          </template>
        </el-table-column>

        <el-table-column align="right" label="含税金额(元)" min-width="140" prop="amount" sortable="custom">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
          </template>
        </el-table-column>
        <el-table-column align="right" label="已核销金额(元)" min-width="150" prop="enter_amount" sortable="custom">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.financeRecord.completeWriteOffAmount" :price="scope.row.financeRecord.completeWriteOffAmount / 100" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="品牌名称" min-width="100">
          <template slot-scope="scope">
            <ToolTip v-if="scope.row.theme && scope.row.theme.length > 5" :content="scope.row.theme"/>
            <div v-else class="ellipsisOne">{{ scope.row.theme || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="结算状态" min-width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.settlementStatus || scope.row.settlementStatus === 0" class="status-dot">
              <span :style="{backgroundColor: getSettlementStatusColor(scope.row.settlementStatus)}" class="dot"/>
              <span>{{ scope.row.settlementStatus | clientSettlementStatus }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="核销状态" min-width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.accountState || scope.row.accountState === 0" class="status-dot">
              <span :style="scope.row.accountState !== 1?{backgroundColor: '#fd8546'}:{backgroundColor: '#31CC9C'}" class="dot"/>
              <span>{{ scope.row.accountState | setAccountState }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="订单状态" min-width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.orderStatus || scope.row.orderStatus === 0" class="status-dot">
              <span :style="{backgroundColor: getOrderStatusColor(scope.row.orderStatus)}" class="dot"/>
              <span>{{ scope.row.orderStatus | orderStatusFilter }}</span>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
      <el-row v-if="clientOrder.total" type="flex" justify="end" class="pagination-area">
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :total="clientOrder.total"
          :page-sizes="[10, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, pager, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </div>

    <!-- <empty-placeholder v-else style="margin-bottom: 24px" /> -->
  </div>
</template>

<script>
import { getClientOrderList } from '@/api/customer';
import { platformList } from '@/api/select';
import tableSelections from '@/mixins/tableSelections';
// import { getList } from '@/api/order';

import { standardFormatNoHour } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import {
  setAccountState,
  clientSettlementStatus,
  orderStatusFilter,
  getOrderStatusColor } from '@/filters/status';
import { settlementStatusOption } from '@/views/order/model/selectData';

import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import platformIcon from '@/components/Common/platformIcon';
import ResourceInfo from '@/components/ResourceInfo';
import Title from '@/components/Title';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
import { LEVEL_CHANGE_TYPE } from '@/utils/const/customer';
import { verificationOptions } from '@/views/project/model/selectData';
export default {
  filters: {
    standardFormatNoHour, moneyFilter,
    setAccountState, clientSettlementStatus,
    orderStatusFilter
  },
  components: { Title, EmptyPlaceholder, platformIcon, ResourceInfo, btnGroup },
  mixins: [tableSelections],
  props: {
    customerId: {
      type: String | Number,
      default: ''
    },
    customerName: {
      type: String,
      default: ''
    },
    filterPrams: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      loading: false,
      page: 1,
      perPage: 10,
      sortType: '',
      sortName: '',
      queryData: {
        timeType: 0
      },
      orderPlatformOption: [],
      clientOrder: {
        items: [],
        total: 0
      },
      ids: '', // 列表当前选中的id
      tableRefName: 'clientOrderRef',
      idKey: 'id',
      customerIdData: this.customerId
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    filterList() {
      return [
        { keyword: 'resourceName', name: '账号', type: 'input', labelWidth: '70px' },
        { keyword: 'orderId', name: '订单编号', type: 'input', labelWidth: '70px' },
        { keyword: 'contactPerson', name: '联系人', type: 'input', labelWidth: '70px' },
        { keyword: 'market', name: '销售', type: 'input', labelWidth: '70px' },
        { keyword: 'theme', name: '品牌名称', type: 'input', labelWidth: '70px' },
        { keyword: 'settleStatus', name: '结算状态', type: 'select', options: settlementStatusOption },
        { keyword: 'accountState', name: '核销状态', type: 'select', options: verificationOptions },
        {
          keyword: 'overdue', name: '逾期情况', type: 'select',
          options: [{ value: -1, label: '全部' }, { value: 0, label: '无逾期' }, { value: 1, label: '有逾期' }]
        },
        {
          keyword: 'process', name: '订单状态', type: 'select',
          options: [
            { value: -1, label: '全部' }, { value: 0, label: '草稿中' }, { value: 1, label: '待发布' }, { value: 3, label: '待审批' },
            { value: 4, label: '待封账' }, { value: 5, label: '封账中' }, { value: 6, label: '已封账' }, { value: 7, label: '已完成' }
          ]
          // { value: 2, label: '待核算' },
        },
        {
          keyword: 'orderPlatformId', name: '下单平台', type: 'select', options: this.orderPlatformOption
        },
        { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate', labelWidth: '70px' },
        { keyword: 'arrivalTime', name: '到账时间', timeType: 'daterange', type: 'rangeDate', labelWidth: '70px' }
      ];
    }
  },
  created() {
    /* this.getData(true);
    this.platformList(); */
    this.customerIdData = Number(this.$route.params.customerId) || this.customerId;
    this.getData(true);
    this.platformList();
  },
  activated() {
    this.customerIdData = Number(this.$route.params.customerId) || this.customerId;
    this.getData(true);
    this.platformList();
  },
  methods: {
    hasRouteAuth,
    getOrderStatusColor,
    sortMethod(a) {
      if (a.prop === 'overdueDayNum') {
        return;
      }
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.getData();
    },
    searchData(params) {
      this.getData(false);
    },
    setParams(isEmit = false) {
      const filterPrams = JSON.parse(JSON.stringify(this.queryData));
      if (filterPrams.createTime && filterPrams.createTime.length === 2) {
        filterPrams.createStartTime = Math.round(filterPrams.createTime[0] / 1000);
        filterPrams.createEndTime = Math.round(filterPrams.createTime[1] / 1000);
      }
      if (filterPrams.arrivalTime && filterPrams.arrivalTime.length === 2) {
        filterPrams.arrivalStartTime = Math.round(filterPrams.arrivalTime[0] / 1000);
        filterPrams.arrivalEndTime = Math.round(filterPrams.arrivalTime[1] / 1000);
      }
      if (filterPrams.orderTime && filterPrams.orderTime.length === 2) {
        filterPrams.orderStartTime = Math.round(filterPrams.orderTime[0] / 1000);
        filterPrams.orderEndTime = Math.round(filterPrams.orderTime[1] / 1000);
      }
      delete filterPrams.orderTime;
      delete filterPrams.createTime;
      delete filterPrams.arrivalTime;
      const params = {
        page: this.page,
        perPage: this.perPage,
        clientId: this.customerIdData,
        sortName: this.sortName,
        sortType: this.sortType,
        enter: 1, // 从哪里请求 1、客户详情 2、创建或编辑结算单
        ...filterPrams
      };
      if (params.process === -1)params.process = '';
      isEmit && this.$emit('seachOrderData', filterPrams);
      return params;
    },
    getData(reset = false) {
      if (reset) this.page = 1;
      // const filterPrams = this.$refs.filterRef ? this.$refs.filterRef.paramsObj : {};
      const params = this.setParams(true);
      this.loading = true;
      getClientOrderList(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          if (res.data.items) {
            res.data.items.forEach(i => {
              if (i.overdueDayNum && !isNaN(Number(i.overdueDayNum))) i.overdueDayNum = Number(i.overdueDayNum);
            });
          }
          this.clientOrder = res.data;
          this.setSelectRow && this.setSelectRow(res.data.items);
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getData();
    },
    beforeExport() {
      const params = this.setParams(false);
      params.ids = this.ids;
      this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExport(params);
    },
    toList() {
      if (!this.hasRouteAuth('crm:customer:customerSettle')) {
        this.$message.warning('客户结算-可读权限不足，请联系管理员!');
        return;
      }
      this.$router.push({
        name: 'customersettle',
        query: { name: this.customerName }
      });
    },
    toBill() {
      if (!this.hasRouteAuth('crm:customerBill:read')) {
        this.$message.warning('客户账单-可读权限不足，请联系管理员!');
        return;
      }
      this.$router.push({
        name: 'customerBill',
        query: { name: this.customerName }
      });
    },
    toCreate() {
      this.$emit('openDialog');
    },
    getSettlementStatusColor(stauts) {
      // 0: '未结算',1: '待提交',2: '待审批',3: '待上传',4: '待封存',5: '已完成'
      let color = '';
      switch (stauts) {
        case 0:
          color = '#406EFF';
          break;
        case 1:
        case 2:
        case 3:
          color = '#FD8546';
          break;
        case 4:
        case 5:
          color = '#31CC9C';
          break;
      }
      return color;
    },
    goOrderDetail(item) {
      this.$router.push({
        name: 'orderDetail',
        params: { orderId: item.id }
      });
    },
    queryClick() {
      this.getData(true);
    },
    // 多选
    tableSelectionChange(e) {
      this.selectList = e;
      this.ids = e.map(item => item.id).join(',');
    },
    queryEmpty() {
      this.queryData = {
        timeType: 0
      };
      this.queryClick();
    },
    levelDialogShow() {
      this.$emit('levelDialogShow', LEVEL_CHANGE_TYPE.PERIOD);
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    resetFilterData() {
      this.queryData = { timeType: 0 };
    }
  }
};
</script>

<style lang="scss" scoped>
.title-tool {
  position: relative;
  .search-btn-style {
    height: 32px;
  }
}
.overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.FilterTool {
  &::v-deep {
    .el-date-editor--datetimerange {
      &.el-input__inner {
        width: 240px !important;
      }
    }
  }
}
.status-dot {
  display: flex;
  align-items: center;
}
.mobile-operate {
  display: flex;
  align-items: center;
  margin-top: 12px;
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
}
</style>
